package com.wgh.product.service.impl;

import com.wgh.product.entity.shop.ProductReview;
import com.wgh.common.vo.PageResult;
import com.wgh.product.mapper.ProductReviewMapper;
import com.wgh.product.service.ProductReviewService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品评价服务实现类
 * @author AI Shop
 */
@Service
public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, ProductReview> implements ProductReviewService {

    @Override
    public PageResult<ProductReview> getReviewPage(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        QueryWrapper<ProductReview> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0);
        
        // 构建查询条件
        if (params != null) {
            if (params.containsKey("productId")) {
                queryWrapper.eq("product_id", params.get("productId"));
            }
            if (params.containsKey("userId")) {
                queryWrapper.eq("user_id", params.get("userId"));
            }
            if (params.containsKey("status")) {
                queryWrapper.eq("status", params.get("status"));
            }
            if (params.containsKey("hasImage")) {
                queryWrapper.eq("has_image", params.get("hasImage"));
            }
            if (params.containsKey("hasVideo")) {
                queryWrapper.eq("has_video", params.get("hasVideo"));
            }
        }
        
        // 查询总数
        long total = baseMapper.selectCount(queryWrapper);
        
        // 查询列表
        Integer start = (pageNum - 1) * pageSize;
        List<ProductReview> reviewList = baseMapper.selectPageList(queryWrapper.getSqlSegment(), start, pageSize);
        
        return new PageResult<>(pageNum, pageSize, total, reviewList);
    }

    @Override
    public PageResult<ProductReview> getReviewsByProductId(Long productId, Integer pageNum, Integer pageSize) {
        QueryWrapper<ProductReview> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId)
                   .eq("del_flag", 0)
                   .eq("status", 1); // 只查询已发布的评价
        
        // 查询总数
        long total = baseMapper.selectCount(queryWrapper);
        
        // 查询列表
        Integer start = (pageNum - 1) * pageSize;
        List<ProductReview> reviewList = baseMapper.selectPageList(queryWrapper.getSqlSegment(), start, pageSize);
        
        return new PageResult<>(pageNum, pageSize, total, reviewList);
    }

    @Override
    public PageResult<ProductReview> getReviewsByUserId(Long userId, Integer pageNum, Integer pageSize) {
        QueryWrapper<ProductReview> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("del_flag", 0);
        
        // 查询总数
        long total = baseMapper.selectCount(queryWrapper);
        
        // 查询列表
        Integer start = (pageNum - 1) * pageSize;
        List<ProductReview> reviewList = baseMapper.selectPageList(queryWrapper.getSqlSegment(), start, pageSize);
        
        return new PageResult<>(pageNum, pageSize, total, reviewList);
    }

    @Override
    public ProductReview getReviewDetail(Long id) {
        return baseMapper.selectById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addReview(ProductReview productReview) {
        productReview.setDelFlag(0);
        productReview.setStatus(0); // 默认待审核状态
        return save(productReview);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateReviewStatus(Long id, Integer status) {
        ProductReview review = new ProductReview();
        review.setId(id);
        review.setStatus(status);
        return updateById(review);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchUpdateReviewStatus(List<Long> ids, Integer status) {
        ProductReview review = new ProductReview();
        review.setStatus(status);
        return update(review, new QueryWrapper<ProductReview>().in("id", ids));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean replyReview(Long id, String replyContent) {
        ProductReview review = new ProductReview();
        review.setId(id);
        review.setReplyContent(replyContent);
        review.setReplyTime(String.valueOf(LocalDateTime.now()));
        return updateById(review);
    }

    @Override
    public Map<String, Object> getReviewStatisticsByProductId(Long productId) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 查询总评价数
        Long totalCount = baseMapper.selectCount(new QueryWrapper<ProductReview>()
                .eq("product_id", productId)
                .eq("del_flag", 0)
                .eq("status", 1));
        
        // 查询有图评价数
        Long imageCount = baseMapper.selectCount(new QueryWrapper<ProductReview>()
                .eq("product_id", productId)
                .eq("del_flag", 0)
                .eq("status", 1)
                .eq("has_image", 1));
        
        // 查询各评分等级的评价数
        Map<String, Integer> scoreMap = new HashMap<>();
        for (int score = 1; score <= 5; score++) {
            Long count = baseMapper.selectCount(new QueryWrapper<ProductReview>()
                    .eq("product_id", productId)
                    .eq("del_flag", 0)
                    .eq("status", 1)
                    .eq("score", score));
            scoreMap.put("score" + score, count.intValue());
        }
        
        statistics.put("totalCount", totalCount);
        statistics.put("imageCount", imageCount);
        statistics.put("scoreMap", scoreMap);
        
        return statistics;
    }

    @Override
    public PageResult<ProductReview> getImageReviewsByProductId(Long productId, Integer pageNum, Integer pageSize) {
        QueryWrapper<ProductReview> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId)
                   .eq("del_flag", 0)
                   .eq("status", 1)
                   .eq("has_image", 1);
        
        // 查询总数
        long total = baseMapper.selectCount(queryWrapper);
        
        // 查询列表
        Integer start = (pageNum - 1) * pageSize;
        List<ProductReview> reviewList = baseMapper.selectPageList(queryWrapper.getSqlSegment(), start, pageSize);
        
        return new PageResult<>(pageNum, pageSize, total, reviewList);
    }

    @Override
    public Double getAverageScoreByProductId(Long productId) {
        // 查询商品的平均评分
        Double averageScore = baseMapper.selectAverageScoreByProductId(productId);
        return averageScore != null ? averageScore : 0.0;
    }
}